<template>
  <div class="comment-list">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error="error"
      error-text="请求失败，点击重新加载"
      :immediate-check="false"
      @load="onLoad"
    >
      <comment-item
        @reply-click="$emit('reply-click', $event)"
        v-for="(item, index) in list"
        :key="index"
        :comment="item"
      ></comment-item>
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment'
import commentItem from './comment-item'
export default {
  name: 'CommentList',
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    type: {
      type: String,
      validate (value) {
        return ['a', 'c'].indexOf(value) !== -1
      },
      default: 'a'
    }
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false
    }
  },
  components: {
    commentItem
  },
  created () {
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad () {
      console.log('触发了onLoad事件')
      try {
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })

        const { results } = data.data
        // console.log(results)
        // this.list = []
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          // 有就更新获取下一页的数据页码
          this.offset = data.data.last_id
        } else {
          // 没有就将 finished 设置结束
          this.finished = true
        }
        console.log(data.data)
        this.$emit('onload-success', data.data)
      } catch (error) {
        this.error = true
        this.loading = true
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
